package org.casper.gc;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 2016年7月4日09:40:53
 */
public class TestGCTunning implements Runnable {

	private static ScheduledExecutorService executorService = Executors
			.newScheduledThreadPool(2);

	private Deque<byte[]> deque;
	private int objectSize;
	private int queueSize;

	public TestGCTunning(int objectSize, int ttl) {
		this.deque = new ArrayDeque<byte[]>();
		this.objectSize = objectSize;
		this.queueSize = ttl * 1000;
	}

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			deque.add(new byte[objectSize]);
			if (deque.size() > queueSize) {
				deque.poll();
			}
		}
	}

	/**
	 * -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps
	 */
	public static void main(String[] args) throws InterruptedException {
		// 这段代码每100毫秒提交两个作业(job)来调度执行。每个作业都模拟特定的生命周期: 创建对象,在预定的时间后释放,接着就不管了,
		// 以允许GC回收内存。
		executorService.scheduleAtFixedRate(new TestGCTunning(
				200 * 1024 * 1024 / 1000, 5), 0, 100, TimeUnit.MILLISECONDS);
		executorService.scheduleAtFixedRate(new TestGCTunning(
				200 * 1024 * 1024 / 1000, 120), 0, 100, TimeUnit.MILLISECONDS);
		TimeUnit.MINUTES.sleep(10);
		executorService.shutdown();
	}
}
